package user.fragment;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.xfengshopping.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

import cn.zzuli.citypicker.bean.CityInfo;
import cn.zzuli.citypicker.utils.CityListLoader;
import cn.zzuli.citypicker.widget.CityPickerBottomDialog;
import utils.TokenUtils;

public class AddAddressActivity extends AppCompatActivity {
    private static final String TAG = "AddAddressActivity";
    private static final String API_URL = "http://47.99.134.126:28019/api/v1/address";

    private EditText nameEt, phoneEt, detailEt;
    private TextView addressTv;
    private CheckBox defaultCb;
    private CityPickerBottomDialog dialog;
    private ProgressDialog progressDialog;
    private boolean isActivityRunning = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_address);

        initViews();
        initCityPicker();
        initProgressDialog();
        setupListeners();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        isActivityRunning = false;
    }

    private void initViews() {
        nameEt = findViewById(R.id.name_et);
        phoneEt = findViewById(R.id.phone_et);
        addressTv = findViewById(R.id.address_tv);
        detailEt = findViewById(R.id.detail_et);
        defaultCb = findViewById(R.id.default_cb);
        CityListLoader.getInstance().init(this);
    }

    private void initCityPicker() {
        dialog = new CityPickerBottomDialog(this);
        dialog.setTitle("选择地址");
        dialog.setOnSubmitClickListener((province, city, district) -> {
            addressTv.setText(String.format("%s %s %s", province.name, city.name, district.name));
            dialog.dismiss();
        });
    }

    private void initProgressDialog() {
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("正在保存地址...");
        progressDialog.setCancelable(false);
    }

    private void setupListeners() {
        findViewById(R.id.back_btn).setOnClickListener(v -> finish());
        findViewById(R.id.address_select_layout).setOnClickListener(v -> dialog.show());

        Button saveBtn = findViewById(R.id.save_btn);
        saveBtn.setOnClickListener(v -> validateAndSubmit());
    }

    private void validateAndSubmit() {
        String name = nameEt.getText().toString().trim();
        String phone = phoneEt.getText().toString().trim();
        String address = addressTv.getText().toString().trim();
        String detail = detailEt.getText().toString().trim();

        if (!validateInputs(name, phone, address, detail)) return;

        String[] addressParts = address.split(" ", 3);
        if (addressParts.length != 3) {
            showError(addressTv, "请选择完整的省市区");
            return;
        }

        saveAddress(
                name,
                phone,
                addressParts[0],  // 省
                addressParts[1],  // 市
                addressParts[2],  // 区
                detail,
                defaultCb.isChecked()
        );
    }

    private boolean validateInputs(String name, String phone, String address, String detail) {
        if (TextUtils.isEmpty(name)) {
            showError(nameEt, "姓名不能为空");
            return false;
        }
        if (TextUtils.isEmpty(phone) || !phone.matches("^1\\d{10}$")) {
            showError(phoneEt, "请输入有效手机号");
            return false;
        }
        if (TextUtils.isEmpty(address)) {
            showError(addressTv, "请选择省市区");
            return false;
        }
        if (TextUtils.isEmpty(detail)) {
            showError(detailEt, "详细地址不能为空");
            return false;
        }
        return true;
    }

    private void showError(View view, String message) {
        if (view instanceof EditText) {
            ((EditText) view).setError(message);
        } else if (view instanceof TextView) {
            ((TextView) view).setError(message);
        }
        view.requestFocus();
    }

    private void saveAddress(String name, String phone, String province,
                             String city, String region, String detail, boolean isDefault) {
        if (!isActivityRunning) return;

        progressDialog.show();

        new Thread(() -> {
            HttpURLConnection connection = null;
            try {
                JSONObject requestBody = new JSONObject();
                requestBody.put("userName", name);
                requestBody.put("userPhone", phone);
                requestBody.put("provinceName", province);
                requestBody.put("cityName", city);
                requestBody.put("regionName", region);
                requestBody.put("detailAddress", detail);
                requestBody.put("defaultFlag", isDefault ? 1 : 0); // 关键参数

                URL url = new URL(API_URL);
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("POST");
                connection.setRequestProperty("Content-Type", "application/json");
                connection.setRequestProperty("token", TokenUtils.getToken(this)); // 传递token
                connection.setConnectTimeout(10000);
                connection.setReadTimeout(10000);
                connection.setDoOutput(true);

                try (OutputStream os = connection.getOutputStream()) {
                    byte[] input = requestBody.toString().getBytes(StandardCharsets.UTF_8);
                    os.write(input, 0, input.length);
                }

                final String response = readResponse(connection);
                runOnUiThread(() -> handleResponse(response));
            } catch (Exception e) {
                Log.e(TAG, "Network error: " + e.getMessage());
                runOnUiThread(() -> {
                    if (isActivityRunning) {
                        progressDialog.dismiss();
                        Toast.makeText(this, "网络连接失败", Toast.LENGTH_SHORT).show();
                    }
                });
            } finally {
                if (connection != null) connection.disconnect();
            }
        }).start();
    }

    private String readResponse(HttpURLConnection connection) throws IOException {
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8)
        );
        StringBuilder response = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();
        return response.toString();
    }

    private void handleResponse(String response) {
        progressDialog.dismiss();
        if (!isActivityRunning) return;

        try {
            JSONObject jsonResponse = new JSONObject(response);
            int resultCode = jsonResponse.getInt("resultCode");
            String message = jsonResponse.optString("message", "未知响应");

            if (resultCode == 200) {
                handleSuccessResponse(jsonResponse);
                Toast.makeText(this, "地址添加成功", Toast.LENGTH_SHORT).show();
            } else if (resultCode == 401) {
                // 处理未认证情况
                TokenUtils.clearToken(this);
                Toast.makeText(this, "登录过期，请重新登录", Toast.LENGTH_SHORT).show();
                startActivity(new Intent(this, LOGIN.login.class));
                finish();
            } else {
                handleErrorResponse(message);
            }
        } catch (JSONException e) {
            Toast.makeText(this, "响应解析失败：" + e.getMessage(), Toast.LENGTH_SHORT).show();
            Log.e(TAG, "JSON解析错误，原始响应：" + response);
        }
    }

    private void handleSuccessResponse(JSONObject response) throws JSONException {
        if (!response.isNull("data")) {
            Object data = response.get("data");
            if (data instanceof JSONObject) {
                JSONObject dataObj = response.getJSONObject("data");
                createAddressResult(dataObj);
            } else if (data instanceof JSONArray) {
                JSONArray dataArray = response.getJSONArray("data");
                if (dataArray.length() > 0) {
                    createAddressResult(dataArray.getJSONObject(0));
                }
            }
        }
        finishWithResult();
    }

    private void createAddressResult(JSONObject data) throws JSONException {
        Address newAddress = new Address(
                data.getInt("addressId"),
                data.getString("userName"),
                data.getString("userPhone"),
                data.getString("provinceName") + " " +
                        data.getString("cityName") + " " +
                        data.getString("regionName") + " " +
                        data.getString("detailAddress"),
                data.getInt("defaultFlag") == 1 // 设置默认状态
        );

        Intent resultIntent = new Intent();
        resultIntent.putExtra("address", newAddress);
        setResult(RESULT_OK, resultIntent);
    }

    private void finishWithResult() {
        if (getResultCode() != RESULT_OK) {
            setResult(RESULT_OK);
        }
        finish();
    }

    private int getResultCode() {
        return 0;
    }

    private void handleErrorResponse(String errorMessage) {
        Toast.makeText(this, "保存失败：" + errorMessage, Toast.LENGTH_LONG).show();
    }
}